<!-- 商品数据 -->
<template>
    <div>
        <ECharts :options="chartOptions"></ECharts>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import ECharts from './ECharts.vue';
import axios from 'axios'

const goods = ref([])
const chartOptions = ref({
    title: {
        text: '商品月销量统计'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
            interval: 0,
            rotate: 30
        }
    },
    yAxis: {
        type: 'value',
        name: '月销量'
    },
    series: [
        {
            data: [],
            type: 'bar',
            name: '销量',
            itemStyle: {
                color: function (params) {
                    // 获取所有销量数据
                    const allData = chartOptions.value.series[0].data;
                    // 创建销量数组的副本并排序
                    const sortedData = [...allData].sort((a, b) => a - b);
                    // 获取前三个最低值
                    const lowestThree = sortedData.slice(0, 3);

                    // 如果当前值在最低的三个值中，显示红色
                    if (lowestThree.includes(params.value)) {
                        return '#F56C6C';  // 最低三个显示红色
                    } else if (params.value === Math.max(...allData)) {
                        return '#67C23A';  // 最高销量显示绿色
                    }
                    return '#409EFF';    // 其他显示蓝色
                }
            }
        }
    ]
})

// 监听商品数据变化，更新图表
watch(goods, (newGoods) => {
    const salesData = newGoods.map(good => good.monthlySales);
    chartOptions.value.xAxis.data = newGoods.map(good => good.name);
    chartOptions.value.series[0].data = salesData;
}, { deep: true })

onMounted(async () => {
    try {
        const response = await axios.get("/get_products", {
            headers: {
                Authorization: sessionStorage.getItem("Authorization"),
            },
        });
        goods.value = response.data.data.map((good) => ({
            ...good,
        }));
    } catch (error) {
        console.error(error);
    }
});
</script>
